<template>
	<a-cascader v-model:value="ids" :options="citys" @change="select" :placeholder="label" />
</template>

<script lang="ts">
import {useCacheStore} from '@/stores/cache'
import {mapState} from 'pinia'

const rules = {
	name: [{ required: true, message: "城市名称必须", trigger: ['change'] }]
};

export default {
	name: "CitySelector",
	props: {
		value: {
			type: Number,
			default: 0
		},
		label: {
			type: String,
			default: '选择城市'
		}
	},
	data() {
		return {
			ids: [],
			rules,
		};
	},
	computed: mapState(useCacheStore, ['citys']),
	mounted() {
		if(this.value){
			const a = String(this.value).match(/\d{2}/g)
			const index1 = this.citys.findIndex((r:any)=>r.value==a[0].padEnd(6, '0'))
			this.ids = [this.citys[index1]?.value, this.value + '']
		}
	},
	methods: {
		select(v: any){
			this.$emit('update:value', typeof(v) == 'object' ? parseInt(v.at(-1)) : 0)
		}
	},
	watch: {
		label(val){
			this.text = val
		},
		value(val){
			if(val){
				const a = String(val).match(/\d{2}/g)
				const index1 = this.citys.findIndex((r:any)=>r.value==a[0].padEnd(6, '0'))
				this.ids = [this.citys[index1]?.value, val + '']
			}
		}
	}
}
</script>
